<template>
  <div class="role-container">
    <header>
      <span>职位管理</span>
      <el-input size="small" placeholder="请输入内容" v-model="searchRole">
        <el-button slot="append" size="small" @click="search" icon="el-icon-search"></el-button>
        <el-button slot="append" size="small" @click="cls">清除</el-button>
      </el-input>
      <span @click="add">
        <i class="el-icon-circle-plus"></i>
        新增职位
      </span>
    </header>

    <div class="a">
      <el-table height="calc(90% - 49px - 16px)" v-loading="loading" class="table" :stripe="true" :header-cell-style="{background:'#eff3f6'}" 
        :data="tableData"
        style="width: 100%">
        <el-table-column
          prop="name"
          label="职位名称"
          width="120">
        </el-table-column>
        <el-table-column
          prop="right"
          label="可访问权限">
          <template slot-scope="scope">
            <el-tag type="success" size="mini" v-for="it in scope.row.right" :key="it.id">
              {{ it }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="职位介绍">
        </el-table-column>
        <el-table-column
          prop="createdAt"
          label="创建时间"
          width="180">
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      :append-to-body="true"
      title="新增职位"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item style="width: 300px" label="职位名称" prop="name">
          <el-input class="input" size="small" type="input" v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="访问权限" prop="right">
          <el-checkbox-group v-model="ruleForm.right">
            <el-checkbox v-for="it in right" :key="it" :label="it" name="type"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="职位介绍">
          <el-input size="small" type="textarea" v-model="ruleForm.remark"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
          <el-button type="primary" @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import { addRoleApi, delRoleApi, roleListApi, updateRoleApi } from '../../../apis/userApi';
  export default {
    data() {
      return {
        a:{},
        searchRole:'',
        loading: true,
        tableData: [],
        // 控制打开
        dialogVisible:false,
        ruleForm:{
          name:'',
          right:[],
          remark:''
        },
        right:[
            '菜单管理',
            '字典管理',
            '用户列表',
            '用户编辑',
            '角色管理',
            '组织管理',
            '产品管理',
            '样品管理',
            '礼品管理'
        ],
        // 判断修改或者添加
        type:'edit',
        // 表单验证
        rules: {
          name: [
            { required: true, message: '请输入活动名称', trigger: 'change' },
            { min: 2, max: 5, message: '长度在 3 到 5 个字符', trigger: 'change' }
          ],
          right:[
            {required: true, message:'请选择一个权限', trigger:'change'}
          ]
        }
      }
    },

    created(){
      this.getRoleList()
    },

    methods: {
      resetForm() {
        this.ruleForm.right = this.a.right
        this.ruleForm.name = this.a.name
        this.ruleForm.remark = this.a.remark
        this.ruleForm.id = this.a.id
      },



      // 查询
      search(){
        this.getRoleList(this.searchRole)
      },
      // 清除查询
      cls(){
        this.searchRole = ''
        this.getRoleList()
      },
      // 添加
      add(){
        this.dialogVisible = true
        this.type = 'add'
      },
      // 修改
      handleEdit(index, row) {
        this.type = 'edit'
        this.a = row
        this.ruleForm.right = row.right
        this.ruleForm.name = row.name
        this.ruleForm.remark = row.remark
        this.ruleForm.id = row.id
        this.dialogVisible = true
      },
      // 关闭对话框
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            this.$refs['ruleForm'].clearValidate()
            this.ruleForm = {
              name:'',
              right:[],
              remark:''
            },
            done();
          })
          .catch(_ => {});
      },
      // 提交
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let right = ''

            this.ruleForm.right.forEach(it => {
                if(it === '菜单管理'){
                  right += '&SYSTEM-01=CRUD'
                }
                if(it === '字典管理'){
                  right += '&SYSTEM-02=CRUD'
                }
                if(it === '用户列表'){
                  right += '&USER-01=CRUD'
                }
                if(it === '用户编辑'){
                  right += '&USER-02=CRUD'
                }
                if(it === '角色管理'){
                  right += '&USER-03=CRUD'
                }
                if(it === '组织管理'){
                  right += '&USER-04=CRUD'
                }
                if(it === '产品管理'){
                  right += '&PRODUCT-01=CRUD'
                }
                if(it === '样品管理'){
                  right += '&PRODUCT-02=CRUD'
                }
                if(it === '礼品管理'){
                  right += '&PRODUCT-03=CRUD'
                }
            })
           
            right = right.slice(1)
            this.ruleForm.right = right
            if(this.type !== 'edit'){
              addRoleApi(this.ruleForm).then(res => {
                if(res.code === 200){
                  this.$message.success('职位添加成功')
                  this.ruleForm = {
                    name:'',
                    right:[],
                    remark:''
                  }
                  this.$refs['ruleForm'].clearValidate()
                  this.dialogVisible = false
                  this.getRoleList()
                }
              })
            }else{
              updateRoleApi(this.ruleForm).then(res => {
                if(res.code === 200){
                  this.$message.success('职位更新成功')
                  this.ruleForm = {
                    name:'',
                    right:[],
                    remark:''
                  }
                  this.dialogVisible = false
                  this.$refs['ruleForm'].clearValidate()
                  this.getRoleList()
                }
              })
              this.dialogVisible = false
            }
          } else {
            return false;
          }
        });
      },
      // 删除权限
      handleDelete(index, row) {
        this.$confirm('确认删除吗？', '操作确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          if(row.id !== 'initial-role'){
            delRoleApi(row.id).then(res => {
              this.$message.success('删除成功')
              this.getRoleList()
            })
          }else{
            this.$message('别他妈乱删')
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 获取权限列表
      getRoleList(name){
        roleListApi({name}).then(res => {
          if(res.code === 200){
            this.tableData = res.data.map((it) => {
              // SYSTEM-01=CRUD&SYSTEM-02=CRUD&
              // USER-01=CRUD&USER-02=CU
              // &USER-03=CRUD&USER-04=CRUD&
              // PRODUCT-01=CRUD&PRODUCT-02=CRUD&PRODUCT-03=CRUD
              let a = it.right.split('&')
              let role = a.reduce((role,it)=>{
                if(it.indexOf('SYSTEM-01') !== -1){
                  role.push('菜单管理')
                }
                if(it.indexOf('SYSTEM-02') !== -1){
                  role.push('字典管理')
                }
                if(it.indexOf('USER-01') !== -1){
                  role.push('用户列表')
                }
                if(it.indexOf('USER-02') !== -1){
                  role.push('用户编辑')
                }
                if(it.indexOf('USER-03') !== -1){
                  role.push('角色管理')
                }
                if(it.indexOf('USER-04') !== -1){
                  role.push('组织管理')
                }
                if(it.indexOf('PRODUCT-01') !== -1){
                  role.push('产品管理')
                }
                if(it.indexOf('PRODUCT-02') !== -1){
                  role.push('样品管理')
                }
                if(it.indexOf('PRODUCT-03') !== -1){
                  role.push('礼品管理')
                }
                return role
              },[])

              it.right = role

              return it
            })
          }

          this.loading = false
        })
      }
    },
  }
</script>



<style lang="less" scoped>
  .role-container{
    width: 100%;
    height: 100%;
    > header {
      width: 100%;
      height: 32px;
      line-height: 32px;
      padding: 8px 16px;
      background: #fff;
      border-bottom: solid 1px #ddd;
      position: relative;
      >span:nth-child(1){
        font-weight: 600;
      }
      > .el-input ::v-deep{
        width: 250px;
        margin-left: 20px;
        height: 12px;
      }
      > span:nth-child(3){
        position: absolute;
        right: 64px;
        cursor: pointer;
      }
    }
    > .a{
      padding: 16px;
      height: 100%;
    }
  }
</style>